<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>考题管理</el-breadcrumb-item>
      <!-- <el-breadcrumb-item>用户列表</el-breadcrumb-item> -->
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <!-- <el-col :span="9">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getQuestionsList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getQuestionsList"
            ></el-button>
          </el-input>
        </el-col> -->
        <el-col :span="2">
          <el-button type="primary" @click="dialogVisible = true"
            >添加问题</el-button
          >
        </el-col>
        <!-- <el-col :span="2">
          <el-button type="primary" @click="">添加考试</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="">添加小测</el-button>
        </el-col> -->
        <el-col :span="2">
          <el-button type="primary" @click="deleteQuestions"
            >删除选中问题</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table
        :data="questionList"
        height="450"
        stripe
        border
        ref="multipleTable"
        @selection-change="handleSelectionChange"
      >
        <!-- 多选栏 -->
        <!-- <el-table-column type="index"> </el-table-column> -->
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="questionContent" width="400" label="问题名称">
        </el-table-column>
        <!-- <el-table-column prop="email" label="邮箱"> </el-table-column> -->
        <el-table-column prop="optionList" label="正确答案">
          <template slot-scope="scope">
            <div v-for="item in scope.row.optionList">
              <div v-if="item.optionIsCorrect == 1">
                {{ item.optionContent }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="questionType" width="150" label="问题类型">
          <!-- <template slot-scope="scope">
            <div v-if="scope.row.questionType == 1">单选题</div>
            <div v-else-if="scope.row.questionType == 2">多选题</div>
          </template> -->
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.questionType == 1">
              单选题
            </el-tag>
            <el-tag type="danger" v-else-if="scope.row.questionType == 2">
              多选题
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="isAdmin" label="管理员">
          <template slot-scope="scope">
            <el-switch
              active-color="#d43c33"
              v-model="scope.row.isAdmin"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column> -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-delete"
              size="mini"
              @click="deleteQuestion(scope.row.questionId)"
              >删除</el-button
            >
            <!-- <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="changeRoleDialog(scope.row)"
            ></el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, , 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加问题的对话框 -->
    <el-dialog
      title="添加问题"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closeAddForm"
    >
      <el-form
        :model="addForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="问题描述" prop="">
          <el-input v-model="addForm.questionContent"></el-input>
        </el-form-item>
        <el-form-item label="问题类型" prop="">
          <!-- 问题类型选择 -->
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题选项" prop="">
          <el-input v-model="addForm.optionList[0].optionContent">
            <template slot="prepend">A</template></el-input
          >
          <el-input v-model="addForm.optionList[1].optionContent">
            <template slot="prepend">B</template></el-input
          >
          <el-input v-model="addForm.optionList[2].optionContent">
            <template slot="prepend">C</template></el-input
          >
          <el-input v-model="addForm.optionList[3].optionContent">
            <template slot="prepend">D</template></el-input
          >
        </el-form-item>
        <el-form-item label="正确答案" prop="" v-if="value">
          <!-- 单选题 -->
          <el-radio-group v-model="radio" v-if="value == 1">
            <el-radio :label="0">A</el-radio>
            <el-radio :label="1">B</el-radio>
            <el-radio :label="2">C</el-radio>
            <el-radio :label="3">D</el-radio>
          </el-radio-group>
          <!-- 多选题 -->
          <el-checkbox-group v-model="checkList" v-if="value == 2">
            <el-checkbox label="A"></el-checkbox>
            <el-checkbox label="B"></el-checkbox>
            <el-checkbox label="C"></el-checkbox>
            <el-checkbox label="D"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAddQuestions">取 消</el-button>
        <el-button @click="addQuestions">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改问题对话框 -->
    <el-dialog
      title="修改问题"
      :visible.sync="editVisible"
      @close="closeEditForm"
    >
      <el-form
        :model="editForm"
        ref="editForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="问题描述" prop="">
          <el-input v-model="editForm.questionContent"></el-input>
        </el-form-item>
        <el-form-item label="问题类型" prop="">
          <!-- 问题类型选择  -->
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="问题选项" prop="">
          <el-input v-model="editForm.optionList[0].optionContent">
            <template slot="prepend">A</template></el-input
          >
          <el-input v-model="editForm.optionList[1].optionContent">
            <template slot="prepend">B</template></el-input
          >
          <el-input v-model="editForm.optionList[2].optionContent">
            <template slot="prepend">C</template></el-input
          >
          <el-input v-model="editForm.optionList[3].optionContent">
            <template slot="prepend">D</template></el-input
          >
        </el-form-item>

        <el-form-item label="正确答案" prop="" v-if="value">
          <!-- 单选题 -->
          <el-radio-group v-model="radio" v-if="value == 1">
            <el-radio :label="0">A</el-radio>
            <el-radio :label="1">B</el-radio>
            <el-radio :label="2">C</el-radio>
            <el-radio :label="3">D</el-radio>
          </el-radio-group>
          <!-- 多选题 -->
          <el-checkbox-group v-model="checkList" v-if="value == 2">
            <el-checkbox label="A"></el-checkbox>
            <el-checkbox label="B"></el-checkbox>
            <el-checkbox label="C"></el-checkbox>
            <el-checkbox label="D"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeEditQuestion">取 消</el-button>
        <el-button @click="editQuestions">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加修改信息对话框 -->
    <!-- <el-dialog
      title="修改用户信息"
      :visible.sync="editVisible"
      @close="closeEditForm"
    >
      <el-form
        :model="editForm"
        :rules="addRules"
        ref="editForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog> -->
    <!-- 修改角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="changeVisible"
      @close="closeChangeRoleForm"
    >
      <p>姓名: {{ userinfo.username }}</p>
      <p>角色: {{ userinfo.role_name }}</p>
      <el-select v-model="selectRole" placeholder="请选择">
        <el-option
          v-for="item in roleList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //定义邮箱的正则表达式
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    //定义手机号的正则表达式
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      // 获取用户列表对象
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 15
      },
      // 问题列表
      questionList: [],
      // 用户修改信息列表
      userEditList: [],
      total: 0,
      dialogVisible: false,
      editVisible: false, //修改用户信息对话框显示与隐藏
      // 添加用户的表单数据
      addForm: {
        optionList: [
          {
            optionContent: "",
            optionIsCorrect: 0
            // optionQuestionId: 0
          },
          {
            optionContent: "",
            optionIsCorrect: 0
            // optionQuestionId: 0
          },
          {
            optionContent: "",
            optionIsCorrect: 0
            // optionQuestionId: 0
          },
          {
            optionContent: "",
            optionIsCorrect: 0
            // optionQuestionId: 0
          }
        ],
        questionContent: "",
        questionType: 0
      },
      editForm: {
        optionList: [
          {
            optionContent: "",
            optionIsCorrect: 0
            // optionQuestionId: 0
          },
          {
            optionContent: "",
            optionIsCorrect: 0
            // optionQuestionId: 0
          },
          {
            optionContent: "",
            optionIsCorrect: 0
            // optionQuestionId: 0
          },
          {
            optionContent: "",
            optionIsCorrect: 0
            // optionQuestionId: 0
          }
        ],
        questionContent: "",
        questionType: 0
      },
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入登录密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" }
          // { validator: checkMobile, trigger: "blur" }
        ]
      },
      changeForm: {},
      changeVisible: false,
      // 用户信息
      userinfo: {},
      selectRole: "",
      roleList: [],
      // 用户删除列表
      questionDeleteIdList: [],
      // 政治面貌选择
      options: [
        {
          value: 1,
          label: "单选题"
        },
        {
          value: 2,
          label: "多选题"
        }
        // {
        //   value: 3,
        //   label: "判断题"
        // },
        // {
        //   value: 4,
        //   label: "填空题"
        // }
      ],
      // 当前选中
      value: "",
      // 正确答案单选框
      radio: "",
      // 正确答案多选框
      checkList: []
    };
  },
  created() {
    this.getQuestionsList();
  },
  methods: {
    // 多选勾选时将对应questionId添加到删除序列
    handleSelectionChange(rows) {
      console.log(rows);
      this.questionDeleteIdList = [];
      rows.forEach(item => {
        this.questionDeleteIdList.push(item.questionId);
      });
      console.log(this.questionDeleteIdList);
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getQuestionsList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getQuestionsList();
    },
    // 获取问题列表
    async getQuestionsList() {
      const { data: res } = await this.$http.get(
        "question/getQuestionList/" + this.queryInfo.pagenum
      );
      if (res.code != 200) {
        return this.$message.error("获取问题列表失败！");
      }
      // 问题列表
      this.questionList = res.data.questionVoList;
      // 总数
      this.total = res.data.total;
    },
    // 关闭对话框清空表单
    closeAddForm() {
      this.$refs.ruleForm.resetFields();
    },
    // 关闭编辑信息对话框
    closeEditForm() {
      this.getQuestionsList();
      this.$refs.editForm.resetFields();
    },
    // 关闭添加问题对话框
    closeAddQuestions() {
      this.dialogVisible = false;
      this.value = "";
      this.addForm = {
        optionList: [
          {
            optionContent: "",
            optionIsCorrect: 0
            // optionQuestionId: 0
          },
          {
            optionContent: "",
            optionIsCorrect: 0
            // optionQuestionId: 0
          },
          {
            optionContent: "",
            optionIsCorrect: 0
            // optionQuestionId: 0
          },
          {
            optionContent: "",
            optionIsCorrect: 0
            // optionQuestionId: 0
          }
        ],
        questionContent: "",
        questionType: 0
      };
    },
    // 添加问题
    async addQuestions() {
      this.$refs.ruleForm.validate(async value => {
        if (!value) return;
        this.addForm.questionType = this.value;
        if (this.value == 1)
          this.addForm.optionList[this.radio].optionIsCorrect = 1;
        else {
          this.checkList.forEach(item => {
            if (item === "A") this.addForm.optionList[0].optionIsCorrect = 1;
            else if (item === "B")
              this.addForm.optionList[1].optionIsCorrect = 1;
            else if (item === "C")
              this.addForm.optionList[2].optionIsCorrect = 1;
            else this.addForm.optionList[3].optionIsCorrect = 1;
          });
          // console.log(this.checkList);
        }
        // 添加问题
        const { data: res } = await this.$http.post(
          "question/addQuestion",
          this.addForm
        );
        if (res.code !== 200) return this.$message.error("添加问题失败！");
        this.$message.success("添加问题成功！");
        // 清空上次
        this.addForm = {
          optionList: [
            {
              optionContent: "",
              optionIsCorrect: 0
              // optionQuestionId: 0
            },
            {
              optionContent: "",
              optionIsCorrect: 0
              // optionQuestionId: 0
            },
            {
              optionContent: "",
              optionIsCorrect: 0
              // optionQuestionId: 0
            },
            {
              optionContent: "",
              optionIsCorrect: 0
              // optionQuestionId: 0
            }
          ],
          questionContent: "",
          questionType: 0
        };
        this.getQuestionsList();
        this.dialogVisible = false;
      });
    },
    // 打开修改用户信息对话框
    async showEditDialog(questionInfo) {
      // return console.log(questionInfo);
      // const { data: res } = await this.$http.get("users/" + id);
      // console.log(res);
      // if (res.meta.status !== 200) {
      //   return this.$message.error("获取用户信息失败！");
      // }
      // this.editForm = res.data;
      this.editForm = questionInfo;
      this.value = this.editForm.questionType;
      if (this.value == 1) {
        for (let i = 0; i < this.editForm.optionList.length; i++) {
          if (this.editForm.optionList[i].optionIsCorrect == 1) this.radio = i;
        }
      } else {
        this.checkList = ["A", "B", "C", "D"];
        for (let i = 0; i < this.editForm.optionList.length; i++) {
          if (this.editForm.optionList[i].optionIsCorrect == 0)
            this.checkList.splice(i, 1);
        }
        // console.log(this.checkList);
      }
      // console.log(this.editForm);
      this.editVisible = true;
    },
    // 修改问题
    editQuestions() {
      this.$refs.editForm.validate(async value => {
        if (!value) return;
        this.editForm.questionType = this.value;
        this.editForm.optionList.forEach(item => {
          item.optionIsCorrect = 0;
        });
        if (this.value == 1) {
          this.editForm.optionList[this.radio].optionIsCorrect = 1;
        } else {
          this.checkList.forEach(item => {
            if (item === "A") this.editForm.optionList[0].optionIsCorrect = 1;
            else if (item === "B")
              this.editForm.optionList[1].optionIsCorrect = 1;
            else if (item === "C")
              this.editForm.optionList[2].optionIsCorrect = 1;
            else this.editForm.optionList[3].optionIsCorrect = 1;
          });
        }
        console.log(this.editForm);
        const { data: res } = await this.$http.post(
          "/question/updateQuestion",
          this.editForm
        );
        console.log(res);
        if (res.code !== 200) {
          this.$message.error("修改问题失败！");
        }
        this.$message.success("修改问题成功！");
        this.editVisible = false;
        this.getQuestionsList();
      });
    },
    // 关闭修改问题对话框
    closeEditQuestion() {
      this.getQuestionsList();
      this.editVisible = false;
    },
    // 删除单个问题
    async deleteQuestion(id) {
      const deleteResult = await this.$confirm("是否删除该问题?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
        // center: true
      }).catch(err => err);
      if (deleteResult === "cancel") return this.$message.info("取消删除！");
      const { data: res } = await this.$http.delete(
        "question/deleteQuestion/" + id
      );
      if (res.code !== 200) return this.$message.error("删除失败！");
      this.$message.success("删除成功！");
      this.getQuestionsList();
    },
    // 删除多个问题
    async deleteQuestions() {
      const deleteResult = await this.$confirm("是否删除选定问题?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
        // center: true
      }).catch(err => err);
      if (deleteResult === "cancel") return this.$message.info("取消删除！");
      const { data: res } = await this.$http.post(
        "question/deleteBatchQuestion",
        this.questionDeleteIdList
      );
      if (res.code !== 200) return this.$message.error("删除失败！");
      this.$message.success("删除成功！");
      this.getQuestionsList();
    },
    //关闭分配角色对话框
    closeChangeRoleForm() {
      this.selectRole = "";
    },
    async changeRoleDialog(user) {
      // 获取角色列表
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败！");
      this.roleList = res.data;
      this.changeVisible = true;
      this.userinfo = user;
    },
    // 修改角色
    async changeRole() {
      if (!this.selectRole) return this.$message.error("请选择要分配的角色！");
      const { data: res } = await this.$http.put(
        `users/${this.userinfo.id}/role`,
        {
          rid: this.selectRole
        }
      );
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("修改角色失败！");
      this.getQuestionsList();
      this.$message.success("修改角色成功！");
      this.changeVisible = false;
    }
  }
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 20px;
}
</style>